﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class CToggle : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    [HideInInspector]
    public Toggle toggle = null;
    [HideInInspector]
    public Image bgImage = null;

    private Vector3 originScale = Vector3.one;
    private Tweener tw = null;
    public bool isTween = true;

    private UnityAction<bool> m_callFun;
    public UnityAction<bool> callFun
    {
        set
        {
            m_callFun = value;
            m_callFun(selected);
        }
        get
        {
            return m_callFun;
        }
    }

    public bool selected
    {
        set
        {
            toggle.isOn = value;
        }
        get
        {
            return toggle.isOn;
        }
    }

    private void Awake()
    {
        toggle = transform.GetComponent<Toggle>();
        bgImage = transform.GetChild(0).GetComponent<Image>();
        originScale = transform.localScale;
        toggle.onValueChanged.AddListener((b) =>
        {
            if (callFun != null) callFun(b);
        });
    }

    private void OnEnable()
    {
        if (!isTween) return;
        if (tw != null) tw.Kill();
        transform.localScale = originScale;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        if (!isTween) return;
        if (!toggle.interactable) return;
        if (tw != null) tw.Kill();
        tw = transform.DOScale(originScale * 0.9f, 0.2f);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        if (!isTween) return;
        if (!toggle.interactable) return;
        if (tw != null) tw.Kill();
        tw = transform.DOScale(originScale, 0.2f);
    }

    public void SetGray(bool b)
    {
        Util.SetUIGray(bgImage, b);
        Util.SetUIGray((Image)toggle.graphic, b);
    }
}
